package com.meida.module.bus.provider.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.log.StaticLog;
import com.google.common.collect.Lists;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.security.OpenHelper;
import com.meida.common.security.OpenUser;
import com.meida.module.bus.client.entity.BusReceiptDeliveryRecord;
import com.meida.module.bus.client.entity.BusReceiptDeliveryReq;
import com.meida.module.bus.client.entity.BusReceiptDeliveryReq;
import com.meida.module.bus.provider.api.soap.SyncSapUtil;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsApiUtil;
import com.meida.module.bus.provider.mapper.BusReceiptDeliveryReqMapper;
import com.meida.module.bus.provider.mapper.BusReceiptDeliveryReqMapper;
import com.meida.module.bus.provider.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 预留发货记录表接口实现类
 *
 * @author flyme
 * @date 2020-12-02
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusRecDeliReqServiceImpl extends BaseServiceImpl<BusReceiptDeliveryReqMapper, BusReceiptDeliveryReq> implements BusRecDeliReqService {

    @Autowired
    private PmsApiUtil pmsApiUtil;

    @Autowired
    private BusMaterialPlan100Service plan100Service;

    @Autowired
    private BusMaterialPlan200Service plan200Service;

    @Autowired
    private BusMaterialService busMaterialService;

    @Autowired
    private BusRecDeliReqConfService busRecDeliReqConfService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusReceiptDeliveryReq brdr, EntityMap extra) {
        return ResultBody.ok();
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusReceiptDeliveryReq> cq, BusReceiptDeliveryReq brdr, EntityMap requestMap) {
//        cq.eq("status", ApiConstants.REC_DELIVERY_RQ_INT);
        cq.like(BusReceiptDeliveryReq.class, "status");
        cq.like(BusReceiptDeliveryReq.class, "projectCode");
        cq.like(BusReceiptDeliveryReq.class, "projectName");
        cq.like(BusReceiptDeliveryReq.class, "majorCode");
        cq.like(BusReceiptDeliveryReq.class, "majorName");
        cq.like(BusReceiptDeliveryReq.class, "packageNo");
        cq.like(BusReceiptDeliveryReq.class, "packageName");
        cq.like(BusReceiptDeliveryReq.class, "userName");
        cq.like(BusReceiptDeliveryReq.class, "appTime");
        cq.like(BusReceiptDeliveryReq.class, "receivedDate");
        cq.like(BusReceiptDeliveryReq.class, "zid");
        cq.like(BusReceiptDeliveryReq.class, "zitem");
        cq.like(BusReceiptDeliveryReq.class, "budat");
        cq.like(BusReceiptDeliveryReq.class, "bldat");
        cq.like(BusReceiptDeliveryReq.class, "bktxt");
        cq.like(BusReceiptDeliveryReq.class, "supplierCode");
        cq.like(BusReceiptDeliveryReq.class, "supplierName");
        cq.like(BusReceiptDeliveryReq.class, "reserveNo");
        cq.like(BusReceiptDeliveryReq.class, "reserveRow");
        cq.like(BusReceiptDeliveryReq.class, "lgort");
        cq.like(BusReceiptDeliveryReq.class, "msgtyFromSap");
        cq.like(BusReceiptDeliveryReq.class, "msgtxFromSap");
        cq.like(BusReceiptDeliveryReq.class, "mblnrFromSap");
        cq.like(BusReceiptDeliveryReq.class, "mblppoFromSap");
        cq.like(BusReceiptDeliveryReq.class, "mjahrFromSap");
        List<String> majorCodes = pmsApiUtil.getAuthMajorCodes(OpenHelper.getUserId());
        if(null != majorCodes) {
            cq.in("majorCode", majorCodes);
        }
        List<String> projectCodeList = pmsApiUtil.getAuthProjectIds(OpenHelper.getUserId());
        if(null != projectCodeList) {
            cq.in("projectCode", projectCodeList);
        }
        return ResultBody.ok();
    }

    @Override
    public Boolean syncSap(List<BusReceiptDeliveryReq> records) throws Exception {
        Boolean rs = Boolean.FALSE;
        if (pmsApiUtil.sapConnectionForRecCheck()) {
            StaticLog.debug("SAP 接口通信开关为关闭。");

            // SAP通信
            List<BusReceiptDeliveryRecord> busReceiptDeliveryRecordList = Lists.newArrayList();

            records.stream().forEach(recordObj -> {
                BusReceiptDeliveryRecord busReceiptDeliveryRecord = new BusReceiptDeliveryRecord();
                BeanUtil.copyProperties(recordObj, busReceiptDeliveryRecord);
                busReceiptDeliveryRecord.setRecDecReqId(recordObj.getRecDecId());
                // 可冲销数量
                busReceiptDeliveryRecord.setCharOffCountCan(recordObj.getDeliveryNumThis());
                busReceiptDeliveryRecord.setSyncStatus(ApiConstants.REC_DELIVERY_FINISH);
                // 累计出库量
                recordObj.setIssuedQty(NumberUtil.add(recordObj.getIssuedQty(), recordObj.getDeliveryNumThis()));
                // 累计出库量 等于 已申请出库量 出库申请单状态改为关闭
                if (recordObj.getIssuedQty().compareTo(recordObj.getRecNumThis()) >= 0) {
                    recordObj.setStatus(ApiConstants.REC_DELIVERY_RQ_CLOSE);
                }
                recordObj.setZid(recordObj.getRecDecId());
                recordObj.setZitem(1);
                recordObj.setDeliveryNumThis(BigDecimal.ZERO);
                recordObj.setLgort(null);
                busReceiptDeliveryRecordList.add(busReceiptDeliveryRecord);
            });
            // 更新添加领料申请记录
            busRecDeliReqConfService.saveOrUpdateBatch(busReceiptDeliveryRecordList);
            return Boolean.TRUE;
        }

        // SAP通信
        Map<String, String> rsMap = SyncSapUtil.syncSap(records, 0);
        List<BusReceiptDeliveryRecord> busReceiptDeliveryRecordList = Lists.newArrayList();

        final Boolean[] errFlg = {Boolean.TRUE};
        records.stream().forEach(recordObj -> {
            BusReceiptDeliveryRecord busReceiptDeliveryRecord = new BusReceiptDeliveryRecord();
            BeanUtil.copyProperties(recordObj, busReceiptDeliveryRecord);
            busReceiptDeliveryRecord.setRecDecReqId(recordObj.getRecDecId());
            // 可冲销数量
            busReceiptDeliveryRecord.setCharOffCountCan(recordObj.getDeliveryNumThis());

            if (ApiConstants.REC_DERVERY_SAP_BACK_ERR.equals(rsMap.get(ApiConstants.MAP_MSGTYFROMSAP))) {
                busReceiptDeliveryRecord.setSyncStatus(ApiConstants.REC_DELIVERY_ERR);
                recordObj.setMsgtyFromSap(ApiConstants.REC_DERVERY_SAP_BACK_ERR);
                recordObj.setMsgtxFromSap(rsMap.get(ApiConstants.MAP_MSGTXFROMSAP));
                if (errFlg[0]) {
                    errFlg[0] = Boolean.FALSE;
                }
            } else {
                busReceiptDeliveryRecord.setSyncStatus(ApiConstants.REC_DELIVERY_FINISH);
                // 累计出库量
                recordObj.setIssuedQty(NumberUtil.add(recordObj.getIssuedQty(), recordObj.getDeliveryNumThis()));
                // 累计出库量 等于 已申请出库量 出库申请单状态改为关闭
                if (recordObj.getIssuedQty().compareTo(recordObj.getRecNumThis()) >= 0) {
                    recordObj.setStatus(ApiConstants.REC_DELIVERY_RQ_CLOSE);
                }
                recordObj.setZid(recordObj.getRecDecId());
                recordObj.setZitem(1);
                recordObj.setDeliveryNumThis(BigDecimal.ZERO);
                recordObj.setLgort(null);
            }
            busReceiptDeliveryRecordList.add(busReceiptDeliveryRecord);
        });
        if (!errFlg[0]) {
            throw new Exception("SAP 出库失败");
        }
        // 更新添加领料申请记录
        busRecDeliReqConfService.saveOrUpdateBatch(busReceiptDeliveryRecordList);
        if (!ApiConstants.REC_DERVERY_SAP_BACK_ERR.equals(rsMap.get(ApiConstants.MAP_MSGTYFROMSAP))) {
            rs = Boolean.TRUE;
        }
        return rs;
    }

    @Override
    public void reqCancel(Long[] selectIds) {
        List<Long> selectIdsList = Arrays.asList(selectIds);
        List<BusReceiptDeliveryReq> recordCancels = Lists.newArrayList();
        OpenUser user = OpenHelper.getUser();
        Collection<BusReceiptDeliveryReq> BusReceiptDeliveryReqs = this.listByIds(selectIdsList);
        BusReceiptDeliveryReqs.stream().forEach(updObj -> {
            updObj.setConfUserId(user.getUserId());
            updObj.setConfUserName(user.getUsername());
            updObj.setStatus(ApiConstants.REC_DELIVERY_RQ_CANCEL);
            updObj.setDelFlg(ApiConstants.DEL_ON);
            recordCancels.add(updObj);
        });
        if (0 < recordCancels.size()) {
            this.updateBatchById(recordCancels);
        }
    }
}
